package com.atguigu.day2;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 100个线程，每个线程加100次，求最后的number值
 */
public class CASDemo {

    public static final Integer COUNT_NUMBER = 100;

    //1 需求:多线程环境【不使用】原子类AtomicInteger保证线程安全（基本数据类型）
    private int number;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        ++number;
    }

    //2.多线程环境【使用】AtomicInteger保证现线程安全（基本类型）
    AtomicInteger atomicInteger =  new AtomicInteger();

    public int getAtomicInteger() {
        return atomicInteger.get();
    }

    public void setAtomicInteger() {
        atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(COUNT_NUMBER);
        for (int i = 1; i <= COUNT_NUMBER; i++) {
            new Thread(() ->{
                for (int j = 1; j <= COUNT_NUMBER; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                countDownLatch.countDown();
            }).start();
        }
        //线程暂停一下
        /*try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("casDemo.getNumber() = " + casDemo.getNumber());
        System.out.println("casDemo.getAtomicInteger() = "+casDemo.getAtomicInteger());
    }


    /*public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(5);

        System.out.println(atomicInteger.compareAndSet(5,25)+"\t"+atomicInteger.get());

        System.out.println(atomicInteger.compareAndSet(5,35)+"\t"+atomicInteger.get());
    }*/
}
